
#include <stdio.h>

#include "decl.h"

Obj     *stack[1024];
char    *stable[1024];
static int index = 0;

typedef struct Symtable Symtable;

struct Symtable
{
    char    *key;
    Obj     *val;
    Symtable *n;
};

static Symtable *table = nil;

void
addSym (char *s, Obj *o)
{
    Symtable *sym = malloc (sizeof (Symtable));
    sym->key = s;
    sym->val = o;
    sym->n = table;
    table = sym;
}

Obj*
lookupSym (char *s)
{
    Symtable *x;
    for (x = table; x; x = x->n)
        if (eqStr (x->key, s))
            return x->val;
    return nil;
}

void
push (char *s, Obj *val)
{
    stable[index]   = s;
    stack[index]    = val;
    index++;
}

void
popN (int n)
{
    index -= n;
}

void
pop ()
{
    index -= 1;
}

Obj*
lookup (char *s)
{
    int i = index-1;
    Obj *o;
    while (i != -1) {
        if (eqStr (s, stable[i]))
            return stack[i];
        i -= 1;
    }
    o = lookupSym (s);
    if (!o)
        printf ("ERROR UNBOUND SYMBOL %s\n", s);
    return o;
}

